package com.erp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.ResponseModel;
import com.erp.entity.MyRoleUser;
import com.erp.entity.MyUser;
import com.erp.entityVo.MyUserVo;
import com.erp.mapper.MyRoleUserMapper;
import com.erp.mapper.MyUserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.erp.Utils.DateFormat;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author  CJ 
 * @since 2021-10-09
 */
@Service
public class MyUserService{

    @Resource
    private MyUserMapper myUserMapper;
    @Resource
    private MyRoleUserMapper myRoleUserMapper;
    /*
    获取用户列表
     */
    public Map<String,Object> userList(String user_name,String nick_name,int page,int limit){
        IPage<Map<String,Object>> userPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        //判断一下是否有搜索条件
        boolean filter_status = false;
        if (StrUtil.isNotEmpty(user_name)){
            wrapper.like("user_name",user_name);
            filter_status = true;
        }
        if (StrUtil.isNotEmpty(nick_name)){
            wrapper.like("nick_name",nick_name);
            filter_status = true;
        }
        if (filter_status){
            userPage = myUserMapper.selectMapsPage(userPage,wrapper);
        }else{
            userPage = myUserMapper.selectMapsPage(userPage,null);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","数据请求成功");
        map.put("count",userPage.getTotal());
        map.put("data",userPage.getRecords());
        return map;
    }

    /*
    通过用户名判断用户是否存在
     */
    public MyUser checkUserExists(String userName){
        return myUserMapper.checkUserExists(userName);
    }
    /*
    新增用户
     */
    public ResponseModel saveUser(MyUserVo myUserVo){
        // 添加用户信息
        myUserVo.setStatus(myUserVo.getStatus());
        myUserVo.setCreateTime(DateFormat.getTime());
        myUserVo.setUpdateTime(DateFormat.getTime());
//        myUserVo.setPassword(DigestUtils.md5DigestAsHex(myUserVo.getPassword().getBytes()));
        int status = myUserMapper.insert(myUserVo);
        if (status > 0){
            // 添加用户和角色表依赖
            MyRoleUser myRoleUser =new MyRoleUser();
            myRoleUser.setRoleId(Convert.toInt(myUserVo.getRoleId()));
            myRoleUser.setUserId(myUserVo.getUserId());
            myRoleUserMapper.save(myRoleUser);
            return ResponseModel.success("用户添加成功");
        }else{
            return ResponseModel.fail("用户添加失败");
        }
    }
    /*
    通过id返回对应数据
     */
    public ModelAndView editView(String userId){
        ModelAndView modelAndView = new ModelAndView();
        Map<String,Object> myUser = myUserMapper.getUser(userId);
        modelAndView.addAllObjects(myUser);
        modelAndView.setViewName("system/user/user-edit");
        return modelAndView;
    }
    /*
    执行用户数据修改
     */
    public ResponseModel editUser(JSONObject data){
        //1.先修改用户信息
        data.put("user_id",data.getInt("user_id"));
        data.put("update_time", DateUtil.now());
        data.put("status",data.getBool("status"));
        if (StrUtil.isNotEmpty(data.getStr("password"))){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            data.put("password",bCryptPasswordEncoder.encode(data.getStr("password")));
        }
//        data.put("password",DigestUtils.md5DigestAsHex(Convert.toStr(data.get("password")).getBytes()));
//        myUserVo.setUpdateTime(DateFormat.getTime());
//        myUserVo.setPassword(DigestUtils.md5DigestAsHex(myUserVo.getPassword().getBytes()));
        myUserMapper.updateUser(data);
        //2.修改角色信息
        MyRoleUser myRoleUser = new MyRoleUser();
        myRoleUser.setUserId(data.getInt("user_id"));
        myRoleUser.setRoleId(data.getInt("roleId"));
        myRoleUserMapper.updateById(myRoleUser);
        return ResponseModel.success();
    }
    /*
    删除用户
     */
    public ResponseModel deleteUser(String user_id){
        String[] strings = user_id.split(",");
        List<String> idList = CollUtil.newArrayList(strings);
        int delCount = myUserMapper.deleteBatchIds(idList);
        if (delCount > 0){
            return ResponseModel.success("删除成功");
        }else{
            return ResponseModel.fail("删除失败,请重新尝试");
        }
    }
    /*
    修改用户状态
     */
    public ResponseModel changeStatus(JSONObject data){
        UpdateWrapper<MyUser> myUserUpdateWrapper = new UpdateWrapper<>();
        //条件构造器Set方法
        //假设只更新一个字段在使用updateWrapper 的构造器中也需要构造一个实体对象,这样比较麻烦。可以使用updateWrapper的set方法
        myUserUpdateWrapper.eq("user_id",data.getInt("userId")).set("status",data.getBool("status"));
//        MyUser myUser = new MyUser();
//        myUser.setStatus(data.getBool("status"));
        int count  = myUserMapper.update(null,myUserUpdateWrapper);
        if (count > 0) {
            return ResponseModel.success("修改用户状态成功");
        }else{
            return ResponseModel.fail("请求失败");
        }
    }

    /*
        根据用户名获取用户
     */
    public MyUser getUserByName(String userName){
        return myUserMapper.getUserByName(userName);
    }
    /*
    根据id获取用户
     */
    public MyUser getUser(String id){

        return myUserMapper.getUserPwd(id);
    }

    /*
        执行密码更新操作
     */
    public int changePwd(MyUser myUser){
        return myUserMapper.updateById(myUser);
    }
}
